package com.example.thymelplay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.thymelplay.dao.MyUserMapper;
import com.example.thymelplay.dao.PermissionMapper;
import com.example.thymelplay.entity.MyUser;
import com.example.thymelplay.entity.Permission;
import com.example.thymelplay.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserServiceImpl implements MyUserService, UserDetailsService {

    @Autowired
    private MyUserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        MyUser user = userMapper.selectOne(new QueryWrapper<MyUser>().eq("username", s));
        if (user!=null){
            List<Permission> pers = permissionMapper.findPermissionByID(user.getUserid());
            Collection<? extends GrantedAuthority> a = pers.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            User user1 = new User(s,user.getUserpwd(),a);
            return user1;
        }
        return null;
    }
}
